package com.wx.timertask;

import com.wx.model.User;
import com.wx.model.templatemessage.First;
import com.wx.model.templatemessage.Keyworld;
import com.wx.model.templatemessage.Remark;
import com.wx.model.templatemessage.WxTemplateMessage;
import com.wx.model.weather.*;
import com.wx.repository.UserRepository;
import com.wx.service.Impl.WXServiceImpl;
import com.wx.util.BDUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * @author ：LiuShihao
 * @date ：Created in 2020/10/20 11:06 下午
 * @desc ：推送天气
 */
@Slf4j
@Component
public class WeatherTask {
    public static Boolean isRun = false;
    /**
     * 每天七点
     */
    public static final String  cron1="0 0 7 * * ? " ;
    /**
     * 每分钟一次
     */
    public static final String  cron2="0 * * * * ? " ;

    @Autowired
    UserRepository repository;
    @Autowired
    WXServiceImpl wxService;
    @Autowired
    BDUtil bdUtil;
    @Scheduled(cron = cron1)
    public void dayReminderTaskp(){
        if (isRun){
            return;
        }
        log.info("------每日天气定时任务来了");
        isRun = true;
        weather();
        isRun = false;
    }

    private void weather() {
        //获得AccessToken
        String redisToken = wxService.getRedisToken();
        String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN";
        String access_token = url.replace("ACCESS_TOKEN", redisToken);
        String zhengzhou = getCityWeatherByCityCode("101180101");
        String shanghai = getCityWeatherByCityCode("101020100");

        List<User> users = repository.findUserByFlag();
        for (User user : users) {
            if (StringUtils.isEmpty(user.getCity()) && StringUtils.isEmpty(user.getOpenID())){
                continue;
            }
            String weather = "";
            if ("郑州".equals(user.getCity())){
                weather = zhengzhou;
            }else{
                weather = shanghai;
            }
            WeatherResponse response = com.alibaba.fastjson.JSONObject.parseObject(weather, WeatherResponse.class);
            WeatherResult result = com.alibaba.fastjson.JSONObject.parseObject(response.getResult(), WeatherResult.class);
            ArrayList<Keyworld> keyworlds = new ArrayList<>();
            First first = new First("今天是" + result.getDate() + "，" + result.getWeek() + "", "#173177");
            Keyworld keyworld0 = new Keyworld(result.getCity(), "#FF2D2D"); //红色
            Keyworld keyworld1 = new Keyworld(result.getWeather(), "#FF0080");
            Keyworld keyworld2 = new Keyworld(result.getTemplow() + "℃", "#FF5809");
            Keyworld keyworld3 = new Keyworld(result.getTemphigh() + "℃", "#46A3FF");
            keyworlds.add(keyworld0);
            keyworlds.add(keyworld1);
            keyworlds.add(keyworld2);
            keyworlds.add(keyworld3);
            Remark remark = new Remark("天气转凉，注意添衣保暖，不要感冒了哦^_^", "#173177");
            List<WeatherIndex> index = com.alibaba.fastjson.JSONObject.parseArray(result.getIndex(), WeatherIndex.class);
            StringBuffer sb1 = new StringBuffer();
            for (WeatherIndex weatherIndex : index) {
                Keyworld keyworld11 = new Keyworld(weatherIndex.getIvalue(), "#173177");
                keyworlds.add(keyworld11);
            }
            net.sf.json.JSONObject first1 = net.sf.json.JSONObject.fromObject(first);
            net.sf.json.JSONObject templateData2 = new net.sf.json.JSONObject();
            templateData2.put("first", first1);
            for (int i = 0; i < keyworlds.size(); i++) {
                net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(keyworlds.get(i));
                templateData2.put("keyword" + i, jsonObject);
            }
            templateData2.put("remark", remark);
            WxTemplateMessage wxTemplateMessage1 = new WxTemplateMessage(user.getOpenID(), "amFxIoRc4fCObVXSXZPQf26NZO7xedq_-rrlIRfDApw", "null", null);
            net.sf.json.JSONObject msgData = net.sf.json.JSONObject.fromObject(wxTemplateMessage1);
            msgData.put("data", templateData2.toString());
            System.out.println(msgData);
            String post = httpClient(access_token, "POST", msgData.toString());
            log.info("推送天气信息情况"+post);
        }
    }

    public String getCityWeatherByCityCode(String cityCode){
        String weather = bdUtil.getWeatherByCitycode(cityCode);
        return weather;
    }

    public String httpClient(String Url,String RequestMethod,String data){
        StringBuffer sb = null;
        try {
            URL url = new URL(Url);
            HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();
            httpUrlConn.setDoInput(true);
            httpUrlConn.setDoOutput(true);
            String s = RequestMethod.toUpperCase();
            httpUrlConn.setRequestMethod(s);
            httpUrlConn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
            if ("GET".equalsIgnoreCase(RequestMethod)){
                httpUrlConn.connect();
            }else {
                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(httpUrlConn.getOutputStream(), "UTF-8"));
                writer.write(data);
                writer.close();
            }
            InputStream inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

            sb = new StringBuffer();
            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                sb.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();
            httpUrlConn.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(sb);
        log.info(sb.toString());
        return sb.toString();
    }

}
